#!/usr/bin/python3
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# ******************************************************************************/
import sys
from argparse import ArgumentParser
from .engine import crawler
from .constant import DEFAULT_SAVE_PATH


def register_parser(parser):
    """
    Register command line arguments
    """
    parser.add_argument("-cve", help="The version number of CVE",
                        default=None, action="store")
    parser.add_argument(
        "-name", help="Name of the affected package", default=None, action="store")

    parser.add_argument("-v", nargs='*', default=None,
                        help="The version number of the affected package")

    parser.add_argument(
        "-o", help="The path to output the CVE result", default=DEFAULT_SAVE_PATH, action="store")

    parser.add_argument(
        "-f", help="CVE file path for batch operation", default=None, action="store")

    parser.set_defaults(func=crawler.run)

    return parser


def _run(args, option_parser=ArgumentParser):
    parser = register_parser(parser=option_parser(
        description='CVE vulnerability repair management'))
    if not args:
        print(parser.parse_args(['-h']))
        return 0
    if ("-cve" not in args or "-name" not in args) and "-f" not in args:
        print("Both the cve number and package name are required, please enter them")
        return 0
    try:
        parser_args = parser.parse_args(args=args)
        parser_args.func(parser_args)
    except Exception:
        return 1
    else:
        return 0


def main(args, exit_code=False):
    """
    CVE gets command-line entry
    """
    errcode = _run(args)
    if exit_code:
        sys.exit(errcode)
    return errcode


if __name__ == "__main__":
    main(sys.argv[1:], exit_code=True)
